<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { SubmissionApi } from '@/api/SubmissionApi.ts'
import { ReloadOutlined } from '@ant-design/icons-vue'
import { JudgeStatus, type SearchRequest, type SubmissionVO } from '@/api/Submission.ts'
import { useUserInfoStore } from '@/stores/UserInfo.ts'
import CodeDialog from './problem/components/codeDialog.vue'

const userInfoStore = useUserInfoStore()
const loading = ref(false)
const submissions = ref<SubmissionVO[]>([])
const onlyMySubmissions = ref(false)
const codeDialogVisible = ref(false)
const selectedSubmission = ref<SubmissionVO | null>(null)

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
})

const searchParams = reactive<SearchRequest>({
  language: null,
  userId: null,
  title: null,
})


const languageOptions = [
  { label: 'Java', value: 'java' },
  { label: 'C++', value: 'cpp' },
  { label: 'Python', value: 'python' },
  { label: 'JavaScript', value: 'javascript' },
  { label: 'Go', value: 'go' },
]

const columns = [
  {
    title: '用户',
    dataIndex: 'userId',
    key: 'userId',
    align: 'center',
    width: '15%'
  },
  {
    title: '题目',
    dataIndex: 'title',
    key: 'title',
    align: 'center',
    width: '20%'
  },
  {
    title: '提交时间',
    dataIndex: 'createTime',
    key: 'createTime',
    align: 'center',
    width: '18%'
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    align: 'center',
    width: '12%'
  },
  {
    title: '运行时间',
    key: 'time',
    align: 'center',
    width: '12%'
  },
  {
    title: '使用内存',
    key: 'memory',
    align: 'center',
    width: '12%'
  },
  {
    title: '语言',
    dataIndex: 'language',
    key: 'language',
    align: 'center',
    width: '12%'
  },
]

// 判题状态中文映射
const statusTextMap: Record<string, string> = {
  [JudgeStatus.ACCEPTED]: '正确',
  [JudgeStatus.WRONG_ANSWER]: '答案错误',
  [JudgeStatus.COMPILE_ERROR]: '编译错误',
  [JudgeStatus.MEMORY_LIMIT_EXCEEDED]: '内存溢出',
  [JudgeStatus.TIME_LIMIT_EXCEEDED]: '超时',
  [JudgeStatus.PRESENTATION_ERROR]: '展示错误',
  [JudgeStatus.WAITING]: '等待中',
  [JudgeStatus.OUTPUT_LIMIT_EXCEEDED]: '输出溢出',
  [JudgeStatus.DANGEROUS_OPERATION]: '危险操作',
  [JudgeStatus.RUNTIME_ERROR]: '运行错误',
  [JudgeStatus.SYSTEM_ERROR]: '系统错误',
}

// 判题状态颜色映射
const statusColorMap: Record<string, string> = {
  [JudgeStatus.ACCEPTED]: 'green',
  [JudgeStatus.WRONG_ANSWER]: 'red',
  [JudgeStatus.COMPILE_ERROR]: 'orange',
  [JudgeStatus.MEMORY_LIMIT_EXCEEDED]: 'red',
  [JudgeStatus.TIME_LIMIT_EXCEEDED]: 'red',
  [JudgeStatus.PRESENTATION_ERROR]: 'orange',
  [JudgeStatus.WAITING]: 'blue',
  [JudgeStatus.OUTPUT_LIMIT_EXCEEDED]: 'red',
  [JudgeStatus.DANGEROUS_OPERATION]: 'red',
  [JudgeStatus.RUNTIME_ERROR]: 'orange',
  [JudgeStatus.SYSTEM_ERROR]: 'red',
}

// 获取状态显示文本
const getStatusText = (status: string) => {
  return statusTextMap[status] || status
}

// 获取状态颜色
const getStatusColor = (status: string) => {
  return statusColorMap[status] || 'default'
}

const fetchData = async () => {
  loading.value = true
  try {
    const params = {
      ...searchParams,
      // 如果勾选了"只看我的提交"，使用当前用户ID
      userId: onlyMySubmissions.value ? (userInfoStore.currentUser?.id || searchParams.userId) : searchParams.userId,
      pageNumber: pagination.current,
      pageSize: pagination.pageSize,
    }
    const data = await SubmissionApi.search(params as any)
    submissions.value = data?.records ?? []
    pagination.current = Number(data?.pageNumber) ?? pagination.current
    pagination.pageSize = Number(data?.pageSize) ?? pagination.pageSize
    pagination.total = Number(data?.totalRow) ?? 0
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.current = 1
  fetchData()
}

const handleReset = () => {
  searchParams.language = null
  searchParams.userId = null
  searchParams.title = null
  onlyMySubmissions.value = false
  pagination.current = 1
  fetchData()
}

const handleTableChange = (pag: any) => {
  pagination.current = pag?.current || 1
  pagination.pageSize = pag?.pageSize || 10
  fetchData()
}

const formatTime = (timeStr: string) => {
  return new Date(timeStr).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 将KB转换为MB显示
const formatMemory = (memoryKB: number) => {
  const memoryMB = memoryKB / 1024
  return memoryMB.toFixed(2)
}

const handleViewCode = (record: SubmissionVO) => {
  // 只有当前用户的提交记录才能查看代码
  if (record.userId !== userInfoStore.currentUser?.id) {
    message.warning('只能查看自己的提交代码')
    return
  }
  selectedSubmission.value = record
  codeDialogVisible.value = true
}

// 检查是否是当前用户的提交
const isCurrentUserSubmission = (record: SubmissionVO) => {
  return record.userId === userInfoStore.currentUser?.id
}

onMounted(() => {
  fetchData()
})
</script>

<template>
  <div class="flex justify-center px-4 py-6">
    <a-card class="w-full max-w-[1080px] rounded-lg shadow-sm">
      <!-- 搜索栏 -->
      <div class="mb-4 flex flex-wrap items-center gap-3">
        <a-input
          v-model:value="searchParams.userId"
          allow-clear
          placeholder="输入用户搜索"
          class="w-40"
        />
        <a-input
          v-model:value="searchParams.title"
          allow-clear
          placeholder="输入题目搜索"
          class="w-52"
        />
        <a-select
          v-model:value="searchParams.language"
          allow-clear
          placeholder="选择语言"
          class="w-36"
        >
          <a-select-option v-for="lang in languageOptions" :key="lang.value" :value="lang.value">
            {{ lang.label }}
          </a-select-option>
        </a-select>
        <a-checkbox v-model:checked="onlyMySubmissions">
          只看我的提交
        </a-checkbox>
        <a-button type="primary" @click="handleSearch">搜索</a-button>
        <a-tooltip title="重置">
          <a-button
            @click="handleReset"
            :shape="'default'"
            class="w-9 h-9 p-0 flex items-center justify-center"
          >
            <template #icon>
              <ReloadOutlined />
            </template>
          </a-button>
        </a-tooltip>
      </div>

      <!-- 表格 -->
      <a-table
        :columns="columns"
        :data-source="submissions"
        :loading="loading"
        rowKey="createTime"
        :pagination="{
          current: pagination.current,
          pageSize: pagination.pageSize,
          total: pagination.total,
          showSizeChanger: false,
        }"
        @change="handleTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'createTime'">
            <span>{{ formatTime(record.createTime) }}</span>
          </template>
          <template v-else-if="column.key === 'status'">
            <a-tag 
              :color="getStatusColor(record.judgeInfo.message)"
              :class="isCurrentUserSubmission(record) ? 'cursor-pointer hover:opacity-80' : 'cursor-not-allowed opacity-60'"
              @click="handleViewCode(record)"
            >
              {{ getStatusText(record.judgeInfo.message) }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'time'">
            <span>{{ record.judgeInfo.time }}ms</span>
          </template>
          <template v-else-if="column.key === 'memory'">
            <span>{{ formatMemory(record.judgeInfo.memory) }}MB</span>
          </template>
          <template v-else-if="column.key === 'language'">
            <a-tag color="blue">{{ record.language }}</a-tag>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 代码弹窗 -->
    <CodeDialog 
      v-model:visible="codeDialogVisible"
      :submission="selectedSubmission"
    />
  </div>
</template>

<style scoped>
</style>
